package com.yingpai.fitness.dvp_2_0.main.fragment.home;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.util.DateFormatUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XGridView;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.yingpai.fitness.dvp_2_0.common.view.statusbar.StatusView;
import com.yingpai.fitness.dvp_2_0.main.activity.ComingSoonActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.LoginActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.WebViewForBannerActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.ShopClassifyActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.ShopSaleActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.assmble.AssmbleShopDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.shop.assmble.AssmbleShopSaleActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.vip.QR_Activity;
import com.yingpai.fitness.dvp_2_0.main.activity.vip.VipCardActivity;
import com.yingpai.fitness.dvp_2_0.main.bean.Dvp_2_1_ShopFragmentBean;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.GlideImageLoader;
import com.yingpai.fitness.entity.vip_card.MemberInfoBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by ASUS on 2018/11/2.
 */

public class ShopFragment extends CommonFragment implements OnRefreshLoadMoreListener {

    @BindView(R.id.status_view)
    StatusView statusView;
    @BindView(R.id.search_shop)
    EditText searchShop;
    @BindView(R.id.shop_fragment_top_banner)
    Banner shopFragmentTopBanner;
    @BindView(R.id.listview)
    XListView listview;
    @BindView(R.id.gridview)
    XGridView gridView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.nested_scroll_view)
    NestedScrollView nested_scroll_view;
    @BindView(R.id.title_bar)
    RelativeLayout title_bar;
    @BindView(R.id.empty)
    LinearLayout empty;
    @BindView(R.id.assemble_rl)
    RelativeLayout assembleRl;
    //    @BindView(R.id.assemble_hs)
//    HorizontalScrollView assembleHs;
//    @BindView(R.id.scare_buying_rl)
//    RelativeLayout scare_buying_rl;
//    @BindView(R.id.scare_buying_hs)listview
//    HorizontalScrollView scare_buying_hs;
//    @BindView(R.id.scare_buying_gridview)
//    XGridView scare_buying_gridview;
    @BindView(R.id.assemble_gridview)
    XGridView assemble_gridview;
    Unbinder unbinder;
    private int pageNum = 1;
    private int pageSize = 10;
    private QuickAdapter<Dvp_2_1_ShopFragmentBean.DataBean.PageInfoBean.RowsBean> quickAdapter;
    private QuickAdapter<Dvp_2_1_ShopFragmentBean.DataBean.MerchandiseTagsBean> gridAdapter;
    private QuickAdapter<Dvp_2_1_ShopFragmentBean.DataBean.GroupBookingBean> assemble_adapter;
    private TokenBean tokenBean;


    public static ShopFragment newInstance() {
        return new ShopFragment();
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_fragment_shop, container, false);
        unbinder = ButterKnife.bind(this, view);
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        title_bar.setVisibility(View.GONE);
        refreshLayout.setOnRefreshLoadMoreListener(this);

        gridAdapter = new QuickAdapter<Dvp_2_1_ShopFragmentBean.DataBean.MerchandiseTagsBean>
                (context, R.layout.item_shop_classify) {
            @Override
            protected void convert(BaseAdapterHelper helper, Dvp_2_1_ShopFragmentBean.DataBean.MerchandiseTagsBean item) {
                helper.setText(R.id.title, item.getName());
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(ShopFragment.this.context)
                        .load(item.getPhotoUrl())
                        .error(R.mipmap.icon_man)
                        .into(photo);
            }
        };
        gridView.setAdapter(gridAdapter);
        gridView.setFocusable(false);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("title", gridAdapter.getItem(position).getName());
                bundle.putString("id", gridAdapter.getItem(position).getId());
                startActivity(ShopClassifyActivity.class, bundle);
            }
        });

//        QuickAdapter<String> scare_buy_adapter = new QuickAdapter<String>(context,R.layout.item_shop_scare_buy) {
//            @Override
//            protected void convert(BaseAdapterHelper helper, String item) {
//                TextView market_price = helper.getView(R.id.market_price);
//                market_price.setPaintFlags(market_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//            }
//        };
//        scare_buying_gridview.setAdapter(scare_buy_adapter);
//        scare_buying_gridview.setFocusable(false);
//        scare_buy_adapter.add("");
//        scare_buy_adapter.add("");
//        scare_buy_adapter.add("");
//        scare_buy_adapter.add("");
//        scare_buy_adapter.add("");
//        scare_buy_adapter.add("");
//        setGridViewParam(scare_buying_gridview,scare_buy_adapter.getCount());
//        scare_buy_adapter.notifyDataSetChanged();

//        scare_buying_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Bundle bundle = new Bundle();
//                bundle.putInt("id",assemble_adapter.getItem(position).getId());
//                startActivity(AssmbleShopDetailActivity.class,bundle);
//            }
//        });

        assemble_adapter = new QuickAdapter<Dvp_2_1_ShopFragmentBean.DataBean.GroupBookingBean>(context,
                R.layout.item_shop_assemble) {
            @Override
            protected void convert(BaseAdapterHelper helper, Dvp_2_1_ShopFragmentBean.DataBean.GroupBookingBean item) {
                TextView assemble_count = helper.getView(R.id.assemble_count);
                assemble_count.setText(item.getGroupType());
                TextView market_price = helper.getView(R.id.market_price);
                market_price.setPaintFlags(market_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                market_price.setText("￥" + item.getCommonPrice());
                helper.setText(R.id.name, item.getName());
                helper.setText(R.id.marketing_price, "￥" + item.getGroupPrice());
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrl().split(",")[0])
                        .error(R.mipmap.default_small_bg)
                        .into(photo);
            }
        };
        assemble_gridview.setAdapter(assemble_adapter);
        assemble_gridview.setFocusable(false);

        assemble_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("id", assemble_adapter.getItem(position).getId());
                startActivity(AssmbleShopDetailActivity.class, bundle);
            }
        });

        quickAdapter = new QuickAdapter<Dvp_2_1_ShopFragmentBean.DataBean.PageInfoBean.RowsBean>(context, R.layout.item_shop_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, Dvp_2_1_ShopFragmentBean.DataBean.PageInfoBean.RowsBean item) {
                helper.setText(R.id.title, item.getName());
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrl())
                        .placeholder(R.mipmap.default_big_bg)
                        .into(photo);
            }
        };
        listview.setAdapter(quickAdapter);
        listview.setFocusable(false);

        searchShop.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(searchShop.getText().toString().trim())) {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "搜索内容");
                        bundle.putInt("type", Constant.NUM_1);
                        bundle.putString("content", searchShop.getText().toString());
                        startActivity(ShopSaleActivity.class, bundle);
                        hintEdit(searchShop);
                        return true;
                    } else {
                        showToast("内容不能为空");
                    }

                }
                return false;
            }
        });


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("title", quickAdapter.getItem(position).getName());
                bundle.putInt("type", Constant.NUM_4);
                bundle.putInt("brandId", quickAdapter.getItem(position).getId());
                startActivity(ShopSaleActivity.class, bundle);
            }
        });


        return view;
    }

    @Override
    protected void initData() {
        showDialog(context, null);
        HttpParams httpParams = new HttpParams();
        httpParams.put("pageNum", pageNum++);
        httpParams.put("pageSize", pageSize);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.SHOP_HOME, httpParams, Url.SHOP_HOME, new Callback<Dvp_2_1_ShopFragmentBean>() {
            @Override
            public void onSuccess(final Dvp_2_1_ShopFragmentBean shopFragmentBean) {
                if (shopFragmentBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    empty.setVisibility(View.GONE);
                    gridAdapter.clear();
                    gridAdapter.addAll(shopFragmentBean.getData().getMerchandiseTags());
                    gridAdapter.notifyDataSetChanged();

                    if (shopFragmentBean.getData().getGroupBooking() != null && shopFragmentBean.getData().getGroupBooking().size() != 0) {
                        assembleRl.setVisibility(View.VISIBLE);
                        assemble_gridview.setVisibility(View.VISIBLE);
                        assemble_adapter.clear();
                        assemble_adapter.addAll(shopFragmentBean.getData().getGroupBooking());
                        assemble_adapter.notifyDataSetChanged();
                    } else {
                        assembleRl.setVisibility(View.GONE);
                        assemble_gridview.setVisibility(View.GONE);
                    }

                    List<String> upBanner = new ArrayList<>();
                    for (int i = 0; i < shopFragmentBean.getData().getUpBanners().size(); i++) {
                        upBanner.add(shopFragmentBean.getData().getUpBanners().get(i).getPhotoUrl());
                    }
                    shopFragmentTopBanner.setOnBannerListener(new OnBannerListener() {
                        @Override
                        public void OnBannerClick(int position) {
                            if (shopFragmentBean.getData().getUpBanners().get(position).getLinkUrl() != null &&
                                    !TextUtils.isEmpty(shopFragmentBean.getData().getUpBanners().get(position).getLinkUrl())) {
                                String linkUrl = shopFragmentBean.getData().getUpBanners().get(position).getLinkUrl();
                                if (shopFragmentBean.getData().getUpBanners().get(position).getLinkUrl().equals("vipCard")) {
                                    startActivity(VipCardActivity.class);
                                }else if(shopFragmentBean.getData().getUpBanners().get(position).getLinkUrl().startsWith("link@")){
                                    String url = linkUrl.substring(linkUrl.indexOf("@")+1, linkUrl.indexOf(","));
                                    String title = linkUrl.substring(linkUrl.indexOf(",")+1, linkUrl.length());
                                    Bundle bundle = new Bundle();
                                    bundle.putString("bannerLink_title", title);
                                    bundle.putString("bannerLink_url",url);
                                    startActivity(WebViewForBannerActivity.class,bundle);
                                }
                            }
                        }
                    });

                    shopFragmentTopBanner.setImages(upBanner)
                            .setDelayTime(3000)
                            .setImageLoader(new GlideImageLoader())
                            .start();

                    if (pageNum - 1 == 1) {
                        quickAdapter.clear();
                        quickAdapter.addAll(shopFragmentBean.getData().getPageInfo().getRows());
                    } else {
                        quickAdapter.addAll(shopFragmentBean.getData().getPageInfo().getRows());
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (shopFragmentBean.getData().getPageInfo().getTotal() % pageSize == 0) {
                        pagecount = shopFragmentBean.getData().getPageInfo().getTotal() / pageSize;
                    } else {
                        pagecount = shopFragmentBean.getData().getPageInfo().getTotal() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }

                } else {
                    if (pageNum - 1 == 1) {
                        empty.setVisibility(View.VISIBLE);
                    } else {
                        empty.setVisibility(View.GONE);
                    }
                    showToast(shopFragmentBean.getMessage() + "");
                }

                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                if (pageNum - 1 == 1) {
                    empty.setVisibility(View.VISIBLE);
                } else {
                    empty.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        statusView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.normal_status));
        shopFragmentTopBanner.setDelayTime(3000);//3秒滑一次
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void setGridViewParam(GridView gridView, int size) {
        int length = 135;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;//密度
        int gridviewWidth = (int) (size * (length + 14) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        gridView.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
        gridView.setColumnWidth(itemWidth); // 设置列表项宽
        gridView.setHorizontalSpacing(24); // 设置列表项水平间距
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setNumColumns(size); // 设置列数量=列表集合数
    }

    @Override
    @OnClick({R.id.search_shop, R.id.to_top, R.id.empty, R.id.assemble_more,R.id.open_qr/*,R.id.scare_buying_more*/})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.search_shop:
                searchShop.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                showSoftInputFromWindow(searchShop);
                break;
            case R.id.to_top:
                nested_scroll_view.scrollTo(0, 0);
                break;
            case R.id.empty:
                onRefresh(refreshLayout);
                break;
            case R.id.assemble_more:
                startActivity(AssmbleShopSaleActivity.class);
                break;
            case R.id.open_qr:
//                startActivity(VipCardActivity.class);
                if(tokenBean!=null){
                    showDialog(context,null);
                    HttpParams httpParams = new HttpParams();
                    httpParams.put("customerId", tokenBean.getId());
                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_INFORMATION,
                            httpParams, Url.GET_INFORMATION, new Callback<MemberInfoBean>() {
                                @Override
                                public void onSuccess(MemberInfoBean memberInfoBean) {
                                    dismissDialog();
                                    if (Constant.REQUEST_SUCCESS.equals(memberInfoBean.getResult())) {
                                        if(memberInfoBean.getMap().getCustomer().isIsMemeber()){
                                            JSONObject jsonObject = new JSONObject();
                                            try {
                                                jsonObject.put("customerId", tokenBean.getId());
                                                jsonObject.put("createTime", DateFormatUtil.getTodaydate());
                                                jsonObject.put("activeTime", 10);
                                                jsonObject.put("QRCodeId", memberInfoBean.getMap().getQRCodeId());
                                                jsonObject.put("expireDate", memberInfoBean.getMap().getCustomer().getExpireDate());
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            Bundle bundle = new Bundle();
                                            bundle.putString("qr_data", jsonObject.toString());
                                            startActivity(QR_Activity.class,bundle);
                                        }else{
                                            startActivity(ComingSoonActivity.class);
                                        }
                                    }else{
                                        showToast(memberInfoBean.getMsg());
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                }
                            });
                } else {
                    startActivity(LoginActivity.class);
                }
                break;
//            case R.id.scare_buying_more:
//                Bundle bundle1 = new Bundle();
//                bundle1.putString("title", quickAdapter.getItem(position).getBrandName());
//                bundle1.putInt("type", Constant.NUM_4);
//                bundle1.putInt("brandId", quickAdapter.getItem(position).getId());
//                startActivity(AssmbleShopSaleActivity.class, bundle1);
//                break;
        }
    }

    public void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager inputMethodManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(editText, 0);
    }

    public void hintEdit(EditText editText) {
        editText.setFocusable(false);
        editText.setFocusableInTouchMode(false);
        InputMethodManager inputMethodManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }
}
